package com.cn.why.springcloudskills.aop;

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.context.annotation.Scope;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * 同步锁Aop具体实现
 */
@Component
@Scope   //单例
@Aspect //面向切面编程
@Order(1) //order越小越是最先执行，但更重要的是最先执行的最后结束。order默认值是2147483647
public class LockAspect {
    /**
     * service 默认是单例的，并发下lock只有一个实例
     */
    private static Lock lock = new ReentrantLock(true);//可重入锁，互斥锁，默认为false,为不公平锁

    //切点层  记录错误的日志
    @Pointcut("@annotation(com.cn.why.springcloudskills.aop.AopLock)")
    public void lockAspect(){
        System.out.println("开始调用切点，并记录错误日志。");
    }

    //切面
    @Around("lockAspect()")
    public Object around(ProceedingJoinPoint joinPoint){
        //加锁
        lock.lock();
        Object obj = null;
        try {
            obj=joinPoint.proceed();
        } catch (Throwable throwable) {
            throwable.printStackTrace();
        } finally {
            //关锁
            lock.unlock();
        }
        return obj;
    }
}
